package recycle.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AesUtils {
    // 固定密钥 16/24/32个字符
    private static final String SECRET_KEY = "RdrIlWf74PMs7v4K";

    private static final Cipher encryptCipher;
    private static final Cipher decryptCipher;

    static {
        try {
            SecretKeySpec SECRET_KEY_SPEC = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
            encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            encryptCipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY_SPEC);

            decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            decryptCipher.init(Cipher.DECRYPT_MODE, SECRET_KEY_SPEC);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            throw new RuntimeException("初始化加密工具失败", e);
        }
    }

    public static String encrypt(String plainText)  {
        byte[] bytes = null;
        try {
            bytes = encryptCipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static String decrypt(String encryptedText)  {
        byte[] bytes = null;
        try {
            bytes = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedText));
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        String originalText = "Hello, World!";

        String encrypted = encrypt(originalText);
        System.out.println("encrypted: " + encrypted);

        String decrypted = decrypt(encrypted);
        System.out.println("decrypted: " + decrypted);

    }
}